using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for WhoisLookup
/// </summary>
namespace WhoIs
{
    public class WhoisLookup
    {
        private Page p = new Page();
        public WhoisLookup()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private System.Net.Sockets.TcpClient tcpclient;
        private System.Net.Sockets.NetworkStream networkstream;

        public string Connect(string domain, string whoIsServer)
        {
            try
            {
                tcpclient = new System.Net.Sockets.TcpClient();
                tcpclient.Connect(whoIsServer, 43);

                networkstream = tcpclient.GetStream();

                byte[] domainArray = System.Text.Encoding.ASCII.GetBytes(domain);
                networkstream.Write(domainArray, 0, domainArray.Length);
                System.IO.StreamReader strmReader = new StreamReader(tcpclient.GetStream());

                string strResponse = string.Empty;
                string strTemp = string.Empty;

                strResponse = ParceResponse(strmReader.ReadToEnd());


                strmReader.Close();
                networkstream.Close();
                tcpclient.Close();

                return strResponse;
            }
            catch (Exception ex)
            {
              return ex.Message;
            }
        }
        private string ParceResponse(string strResponse)
        {
            // Regex re = new Regex(
            string str = string.Empty;
            DataSet ds = new DataSet();
            ds.ReadXml(p.Server.MapPath("Parser.xml"));
            string domainName = string.Empty;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                MatchCollection mc = Regex.Matches(strResponse, dr[0].ToString());
                foreach (Match m in mc)
                {

                    str += m.Value;

                    if (m.Value.IndexOf("Domain Name:") != -1)
                    {
                        domainName = m.Value.Replace("Domain Name:", "").Trim();
                    }
                    if (m.Value.IndexOf("Whois Server:") != -1)
                    {
                        WhoisLookup wc = new WhoisLookup();

                        string whoisServer = m.Value.Replace("Whois Server:", "").Trim();
                        string s = wc.Connect(domainName + Environment.NewLine, whoisServer);
                        return s;
                    }
                }
            }
            return strResponse;
        }
    }
}


